package com.hdu;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 两阶段终止模式
 */
@Slf4j
public class TwoPhaseTermination {


    public static void main(String[] args) {
        TwoPhaseTermination twoPhaseTermination = new TwoPhaseTermination();
        twoPhaseTermination.start();
        // 3s后打断
        try {
            TimeUnit.SECONDS.sleep(3);
            twoPhaseTermination.stop();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    private final int STOP = 0;
    private final int RUNNING = 1;
    private final AtomicInteger STATUS = new AtomicInteger(STOP);
    private Thread monitor;


    /**
     * 启动监控线程
     */
    public void start() {
        if (STATUS.compareAndSet(STOP, RUNNING)) {
            monitor = new Thread(() -> {
                while (true) {
                    if (Thread.currentThread().isInterrupted()) {
                        log.info("被打断了, 开始料理后事");
                        break;
                    }
                    try {
                        TimeUnit.SECONDS.sleep(2);
                        log.info("执行监控逻辑");
                    } catch (InterruptedException e) {
                        // 重新设置打断标记
                        Thread.currentThread().interrupt();
                    }
                }
            });
            monitor.start();
        }
    }

    /**
     * 停止监控线程
     */
    public void stop() {
        if (STATUS.compareAndSet(RUNNING, STOP)) {
            monitor.interrupt();
        }
    }

}
